<template lang="pug">
  .tab-1
    Table.hasTitle-table.beautiful-table(:columns="setThead" :data="contractList")
      .pr-24.pl-24(slot="header")
        .pull-right.table-title-btns
          Button.mr-15(type="info" @click="createContact") 新建合同
      template(slot-scope="{ row, index }" slot="action")
        Button.mr-5(type="text" size="small" @click="progressBtn(row.id, row.contractNo, row.contractType)") 进度查看
        Poptip(trigger="hover")
          div(slot="content")
            .u-d-info(@click="downFile(row.id)") 合同下载
            .u-d-info(@click="downSelaFile(row.id)") 盖章合同下载
          Button.mr-5(type="text" size="small") 下载
        //- Button.mr-10(type="text" size="small" @click="downFile(row.id)") 合同下载
        //- Button.mr-10(type="text" size="small" @click="downSelaFile(row.id)") 盖章合同下载
        Button.mr-5(type="text" size="small" @click="openUpdateModal(row.id)") 盖章合同上传
        Poptip(trigger="hover")
          div(slot="content")
            .u-d-info(@click="restartBtn(row.id, row.contractNo, row.contractType)") 重新发起
            .u-d-info(@click="retrieveBtn(row.id, row.contractNo, row.contractType)") 回收
          Button(type="text" size="small") 操作
      .clearfix.pl-20.pr-20(slot="footer")
        Page(:total="total" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    Modal(v-model="createModal" title="新建合同" width="900")
      Form(ref="formValidate" :model="formValidate" :label-width="130")
        Row(type="flex" justify="start")
          Col(span="24")
            FormItem.mb-5(label="合同类型：")
              RadioGroup(type="button" v-model="contractType" @on-change="contractTypeChange")
                Radio.mr-30(label="标准合同") 标准合同
                Radio(label="非标准合同") 非标准合同
          Col(span="24")
            FormItem.ivu-form-item-required.mb-5(label="销售产品类型：" )
              Select(v-model="formValidate.productType" clearable @on-change="productTypeChange")
                Option(v-for="(item,index) in productTypeList" :value="item.text" :key="index") {{item.text}}
          template(v-if="contractType === '标准合同'")
            Col(span="24")
              FormItem.ivu-form-item-required.mb-5(label="商务合同模板：")
                Select(v-model="formValidate.templateID" clearable @on-change="templateIDChange")
                  Option(v-for="(item,index) in templateList" :value="item.id" :key="index") {{item.fileName}}
          Col(span="24")
            FormItem.ivu-form-item-required.mb-5(label="印章类型：")
              Select(v-model="formValidate.sealType" clearable)
                Option(v-for="(item,index) in selaTypeList" :value="item.text" :key="index") {{item.text}}
            template(v-for="(item,index) in templateFields")
              Col(span="12")
                FormItem.mb-5.ivu-form-item-required(:label="item.field + '：'")
                  Input(v-model="item.value" type="text")
          template(v-if="contractType === '非标准合同'")
            Col(span="24")
              FormItem.ivu-form-item-required(label="选择文件：")
                Upload(
                  :before-upload="createHandleUpload"
                  ref="addUpload"
                  :show-upload-list="true"
                  action=""
                  accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                  :format="['doc','docx']"
                  )
                  Button(type="info" icon="ios-cloud-upload-outline") 点击上传
                .my-tag.mr-20(v-if="templateFile")
                  .my-tag-inner {{fileName}}
                  .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile")
                .ivu-form-item-error-tip(v-if="hasFile") 文件不能为空
      div(slot="footer")
        Button(@click="createModal = false") 取消
        Button(v-if="contractType === '标准合同'" type="info" @click="handleSubmit") 保存(标准)
        Button(v-else type="info" @click="handleSubmit_f") 保存(非标准)
    Modal(v-model="updateModal" title="盖章合同上传")
      Upload(
        :before-upload="selaContractUpload"
        type="drag"
        action=""
        accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        :format="['doc','docx']")
        div(style="padding: 20px 0")
          Icon(type="ios-cloud-upload" size="52" style="color: #3399ff")
          p 点击或者直接将文件拖至此处
      .my-tag.mr-20(v-if="selaContractFile")
        .my-tag-inner {{selaContractName}}
        .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteSelaFile")
      div(slot="footer")
        Button(@click="updateModal = false") 取消
        Button(type="info" @click="upDateSelaFile") 上传
</template>

<script>
import theadMixin from '../../theadMixin.js'
import commerceContractApi from '@/api/commerceContract.api.js'

export default {
  props: {
    productTypeList: Array,
    selaTypeList: Array,
    contractList: Array,
    total: Number,
    PageIndex: Number,
    PageSize: Number
  },
  mixins: [theadMixin],
  components: {
  },
  data () {
    return {
      thead: ['contractNo', 'applyUserName', 'applyDepartment', 'applyTime', 'contractType', 'sealType', 'contractTemplate', 'productType', 'process', 'action'],
      createModal: false,
      updateModal: false,
      contactId: '', // 合同id
      contractType: '标准合同', // 合同类型
      templateList: [], // 模板列表
      templateFields: [], // 模板字段
      templateFile: null, // 非标准文件模板
      selaContractFile: null, // 盖章合同模板
      selaContractName: '', // 盖章合同名称
      hasFile: false,
      formValidate: {
        productType: '',
        templateID: '', // 模板ID
        sealType: ''
      }
    }
  },
  computed: {
    setThead () {
      return this.getTableColumns(this.thead)
    }
  },
  methods: {
    progressBtn (id,no,type) {
      console.log(111)
      this.$emit('get-progress', {
        id,
        no,
        type
      })
    },
    // 重新发起
    restartBtn (id,no,type) {
      commerceContractApi.RestartContractWorkFlow({
        ID: id,
        ContractNo: no,
        ContractType: type,
        Remark: ''
      }).then(res => {
        if (res.data.success) {
          this.$Message.info(res.data.message)
          this.$emit('get-list', {
            PageIndex: 1
          })
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 回收流程
    retrieveBtn (id,no,type) {
      commerceContractApi.BackWorkFlow({
        ID: id,
        ContractNo: no,
        ContractType: type,
        Remark: ''
      }).then(res => {
        if (res.data.success) {
          this.$emit('get-list', {
            PageIndex: 1
          })
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    createContact () {
      this.createModal = true
    },
    openUpdateModal (id) {
      this.contactId = id
      this.updateModal = true
    },
    // 保存按钮-标准
    handleSubmit (name) {
      let allHas = this.templateFields.every(item => {
        return item.value != ''
      })
      if (allHas) {
        this.postStandardContract()
      } else {
        this.$Message.warning('有必填项未填!')
      }
    },
    // 保存按钮-非标准
    handleSubmit_f () {
      let arr = [this.formValidate.productType, this.formValidate.sealType]
      let allHas = arr.every(item => {
        return item != ''
      })
      if (allHas) {
        if (this.templateFile) {
          this.PostNonstandardContract()
        } else {
          this.hasFile = true
        }
      } else {
        this.$Message.warning('有必填项未填!')
      }
    },
    // 获取合同模板
    getTemplateList () {
      commerceContractApi.GetTemplates({
        productType: this.formValidate.productType
      }).then(res => {
        if (res.data.success) {
          this.templateList = res.data.data
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 提交标准合同
    postStandardContract () {
      commerceContractApi.PostStandardContract(Object.assign(
        this.formValidate,
        { FieldValues: this.templateFields })
      ).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.createModal = false
          this.formValidate = {
            productType: '',
            templateID: '', // 模板ID
            sealType: ''
          }
          this.templateFields = []
          this.$emit('get-list', {
            PageIndex: 1
          })
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 提交非标准合同
    PostNonstandardContract () {
      let formData = new FormData()
      formData.append('producttype', this.formValidate.productType)
      formData.append('sealType', this.formValidate.sealType)
      formData.append('atta', this.templateFile)
      commerceContractApi.PostNonstandardContract(formData).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.createModal = false
          this.templateFile = null
          this.fileName = ''
          this.hasFile = false
          this.formValidate = {
            productType: '',
            templateID: '', // 模板ID
            sealType: ''
          }
          this.$emit('get-list', {
            PageIndex: 1
          })
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    productTypeChange (val) {
      console.log(val)
      if (val) {
        this.getTemplateList()
      } else {
        this.templateList = []
      }
    },
    templateIDChange (val) {
      console.log(val)
      if (val) {
        this.getTemplateFields()
      } else {
        this.templateFields = []
      }
    },
    // 获取模板字段
    getTemplateFields () {
      commerceContractApi.GetTemplateFields({
        TemplateID: this.formValidate.templateID
      }).then(res => {
        if (res.data.success) {
          this.templateFields = res.data.data
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 上传模板附件
    createHandleUpload (file) {
      console.log(file)
      this.templateFile = file
      this.fileName = file.name
      this.hasFile = false
      return false
    },
    // 盖章合同上传
    selaContractUpload (file) {
      console.log(file)
      this.selaContractFile = file // 盖章合同模板
      this.selaContractName = file.name // 盖章合同名称
      return false
    },
    upDateSelaFile () {
      if (this.selaContractFile) {
        let formData = new FormData()
        // formData.append('contractid', this.contactId)
        formData.append('atta', this.selaContractFile)
        commerceContractApi.PostSelaContract(this.contactId, formData).then(res => {
          if (res.data.success) {
            this.$Message.success(res.data.message)
            this.updateModal = false
            this.selaContractFile = null // 盖章合同模板
            this.selaContractName = '' // 盖章合同名称
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 10,
              closable: true
            })
          }
        })
      } else {
        this.$Message.warning('请先选择需要上传的文件')
      }
    },
    deleteFile () {
      this.templateFile = null
      this.fileName = ''
    },
    deleteSelaFile () {
      this.selaContractFile = null // 盖章合同模板
      this.selaContractName = '' // 盖章合同名称
    },
    contractTypeChange () {
      this.templateFile = null
      this.fileName = ''
      this.hasFile = false
      this.templateFields = []
      this.formValidate = {
        productType: '',
        templateID: '', // 模板ID
        sealType: ''
      }
    },
    pageChangeFn (val) {
      this.$emit('get-list', {
        PageIndex: val
      })
    },
    onpageSizeChange () {

    }
  }
}
</script>

<style>

</style>
